package com.wenjiang.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wenjiang.entity.MallAdmin;
import com.wenjiang.entity.MallAdminUser;
import com.wenjiang.entity.MallPermission;
import com.wenjiang.mapper.MallAdminMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 处理登陆 账号登陆的具体逻辑 并把用户信息加载到 spring security 的用户信息容器当中
 */
@Component
@Slf4j
public class AdminUserDetailsService implements UserDetailsService {
    // 注入mapper
    @Autowired
    MallAdminMapper mallAdminMapper;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        log.info("开始加载用户的权限信息");

        MallAdmin mallAdmin =new MallAdmin();
        // 授权实体
        MallAdminUser mallAdminUser = new MallAdminUser();

        //用户为空
        if (StringUtils.isEmpty(username)){
            // 抛出用户名异常
            throw  new UsernameNotFoundException("用户名不存在");
        }

        //查询用户
        mallAdmin=mallAdminMapper.selectOne(new QueryWrapper<MallAdmin>().eq("user_name", username));
        //用户不存在
        if(mallAdmin==null){
            return null;
        }

        // 用户是否被封禁
//        if

        BeanUtil.copyProperties(mallAdmin, mallAdminUser);

        // 查询用户所用有的权限
        List<MallPermission> userPermission = mallAdminMapper.getUserPermission(mallAdminUser.getUserId());
        //新建授权列表
        List<GrantedAuthority> grantedAuthorities= new ArrayList<>();
        //设置已授予的用户权限
        userPermission.forEach((item)->{
            grantedAuthorities.add(new SimpleGrantedAuthority(item.getPermKey()));
        });

        mallAdminUser.setAuthorities(grantedAuthorities);

        return mallAdminUser;
    }
}
